<template>
  <div id="app">
    <div class="background"></div>
    <div class="chat-box">
      <div class="chat-box-left">
        <div class="search-box">
          <div style="padding: 20px 20px 0">
            <input class="search-user"
                   id="search-user"
                   type="text"
                   :placeholder="searchPlaceholder"
                   v-model="searchInput"
                   @keyup.enter="searchChatList"
                   @focus="showSearchedList"
                   @blur="hideSearchedList"
            >
            <div class="icon-clear" v-show="searchInput !== ''" @click="clearSearchInput">
              <svg t="1627178286402" class="icon icon-clear-style" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2265" width="200" height="200"><path d="M810.666667 273.493333L750.506667 213.333333 512 451.84 273.493333 213.333333 213.333333 273.493333 451.84 512 213.333333 750.506667 273.493333 810.666667 512 572.16 750.506667 810.666667 810.666667 750.506667 572.16 512z" p-id="2266" fill="#2c2c2c"></path></svg>
            </div>
          </div>
        </div>
        <div v-if="searchIndex === 1">
          <div class="chat-user-list">
            <p v-show="searchInput === ''" style="text-align: center; color: #cccccc">还没有对话</p>
            <div>
              <div v-for="(item,index) in searchedChatList" :key="index">
                <div class="chat-user"
                     @click="()=>{getMessageRecord(item.receiver,item.listId,item.avatar,item.nickname);setListIdRead(item.listId,index)}"
                >
                  <div style="display: inline">
                    <img class="user-list-avatar" :src="item.avatar">
                    <i :class="item.isOnline === 1 ? 'tip-online':'tip-offline'"></i>
                  </div>
                  <div style="display: inline-block">
                    <div class="user-list-name">
                      {{ item.nickname }}
                    </div>
                    <p class="latest-message">
                      {{ item.latestMessage }}
                    </p>
                  </div>
                  <div style="display: inline-block; float: right">
                    <span class="latest-time" style="display: block">{{ item.latestTime }}</span>
                    <div class="tip-unRead" v-if="item.unread !== 0">
                      <span> {{ item.unread }} </span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div v-else>
          <p class="text-resent">最近联系</p>
          <div class="chat-user-list">
            <div v-for="(item,index) in chatList" :key="index">
              <div class="chat-user"
                   v-if="item.listIndex === 1"
                   @click="()=>{getMessageRecord(item.receiver,item.listId,item.avatar,item.nickname);setListIdRead(item.listId,index)}"
              >
                <div style="display: inline">
                  <img class="user-list-avatar" :src="item.avatar">
                  <i :class="item.isOnline === 1 ? 'tip-online':'tip-offline'"></i>
                </div>
                <div style="display: inline-block">
                  <div class="user-list-name">
                    {{ item.nickname }}
                  </div>
                  <p class="latest-message">
                    {{ item.latestMessage }}
                  </p>
                </div>
                <div style="display: inline-block; float: right">
                  <span class="latest-time" style="display: block">{{ item.latestTime }}</span>
                  <div class="tip-unRead" v-if="item.unread !== 0">
                    <span> {{ item.unread }} </span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

      </div>

      <div class="chat-box-right">
        <div v-show="listId === 0" style="text-align: center">
          <span class="name">
            CMUP
          </span>
        </div>
        <div v-show="listId !== 0">
          <div class="user-info-name">
            {{ nickname }}
          </div>
          <div class="message-box" ref="toBottom">

            <div class="message-item">
              <div v-for="(item,index) in messageList" :key="index">
                <div class="message-time" v-if="item.sendDate !== null">
                  {{ item.sendDate }}
                </div>

                <div style="display: flex;flex-flow: column;">
                  <div style="display: flex;margin-left: auto;" v-if="item.isMine === true">
                    <div class="my-bubble">
                      <div class="message-content">
                        {{ item.content }}
                      </div>
                    </div>
                    <div>
                      <img class="user-list-avatar" :src="item.avatar" style="float: right">
                    </div>
                  </div>
                  <div v-else>
                    <img class="user-list-avatar" :src="item.avatar" style="position:absolute;">
                    <div class="bubble" style="display: inline-block">
                      <div class="message-content">
                        {{ item.content }}
                      </div>
                    </div>
                  </div>
                </div>

              </div>
            </div>
          </div>

          <div class="send-box">
            <div class="send-item">
              <div class="icon-style" @click="pushEmoji">
                <svg class="Zi Zi--Emotion EmoticonTool-icon ToolBar-Icon icon-color" fill="currentColor" viewBox="0 0 24 24" width="24" height="24"><path d="M7.523 13.5h8.954c-.228 2.47-2.145 4-4.477 4-2.332 0-4.25-1.53-4.477-4zM12 21a9 9 0 1 1 0-18 9 9 0 0 1 0 18zm0-1.5a7.5 7.5 0 1 0 0-15 7.5 7.5 0 0 0 0 15zm-3-8a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3zm6 0a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3z"></path></svg>
              </div>
              <div class="icon-style">
                <svg class="Zi Zi--AddImage ToolBar-Icon icon-color" fill="currentColor" viewBox="0 0 24 24" width="24" height="24"><path d="M13.25 5.5H6.868c-.755 0-1.368.613-1.368 1.368v10.264c0 .755.613 1.368 1.368 1.368h10.264c.755 0 1.368-.613 1.368-1.368V10.75H20v6.467A2.783 2.783 0 0 1 17.217 20H6.783A2.783 2.783 0 0 1 4 17.217V6.783A2.783 2.783 0 0 1 6.783 4h6.467v1.5zM8.158 13.4a1.033 1.033 0 0 1 1.744-.078l.258.37a.782.782 0 0 0 1.303-.031l1.332-2.113a1.173 1.173 0 0 1 2.01.043l2.03 3.537A1.25 1.25 0 0 1 15.748 17H8.25a1.252 1.252 0 0 1-1.085-1.873l.992-1.728zM9.5 11a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3zm3.75-5.5a.75.75 0 1 1 0-1.5.75.75 0 0 1 0 1.5zM18.5 4V2.25a.75.75 0 1 1 1.5 0V4h1.75a.75.75 0 1 1 0 1.5H20v1.75a.75.75 0 1 1-1.5 0V5.5h-1.75a.75.75 0 1 1 0-1.5h1.75zm.75 7.5a.75.75 0 1 1 0-1.5.75.75 0 0 1 0 1.5z"></path></svg>
              </div>
            </div>
            <textarea class="send-textarea"
                      id="send-textarea"
                      rows="3"
                      v-model="content"
                      @keyup.enter = "sendMsg"
            ></textarea>
            <button :class="content.length === 0 ? 'send-button-none':'send-button'" @click="()=>{sendMsg()}">发送</button>
          </div>
        </div>

      </div>
    </div>
  </div>
</template>

<script>

export default {
  name: "chat",

  data() {
    return {
      searchInput: '',
      searchedChatList: '',
      searchIndex: 0,
      searchPlaceholder: '搜索联系人',
      chatList: [],
      listId: 0,
      userNoSelf: window.localStorage.getItem('userNo'),
      avatarSelf: window.localStorage.getItem('userProfile'),
      nicknameSelf: '咕噜',
      userNo: '',
      nickname: '',
      avatar: '',
      messageList: [],
      content: '',
    }
  },

  methods: {
    initWebSocket(){//初始化websocket
      this.websock = new WebSocket("ws:39.105.106.111:8080/community/websocket/" + this.userNoSelf);//这里面的this都指向vue
      this.websock.onopen = this.websocketonopen;
      this.websock.onerror = this.websocketonerror;
      this.websock.onclose = this.websocketonclose;
      this.websock.onmessage = this.websocketonmessage;
    },
    websocketonopen(){ //打开连接
      console.log("WebSocket连接成功")
    },
    websocketonerror(){ //连接失败
      console.log("WebSocket连接失败");
    },
    websocketonmessage: function (e) {
      console.log(e)
      let data = JSON.parse(e.data);
      let i = this.messageList.length
      let message = {
        avatar: '',
        content: data.content,
        isMine: '',
        isRead: 0,
        listId: data.listId,
        messageId: data.messageId,
        nickname: '',
        receiver: data.receiver,
        sendTime: data.sendTime,
        sendDate: '',
        sender: data.sender,
        type: 1,
      }
      if(window.sessionStorage.getItem('receiver') !== null) {
        message.sendDate = this.setFirstSendTime(message.sendTime)
        window.sessionStorage.clear()
      } else {
        message.sendDate = this.setSendTime(this.messageList[i-1].sendTime,data.sendTime)
      }
      if(data.sender == this.userNoSelf) {
        message.avatar = this.avatarSelf
        message.isMine = true
        message.nickname = this.nicknameSelf
      } else {
        message.avatar = this.avatar
        message.isMine = false
        message.nickname = this.nickname
      }
      for(let j=0;j<this.chatList.length;j++) {
        if(this.chatList[j].listId == message.listId) {
          this.chatList[j].latestMessage = message.content
          this.chatList[j].latestTime = this.setLatestTime(message.sendTime)
          if(message.isMine === false)
            this.chatList[j].unread += 1
        }

      }
      this.messageList.push(message)
    },
    websocketonclose(){ //关闭连接
      console.log("WebSocket关闭");
    },
    sendMsg() {
      let data = {
        sender: this.userNoSelf,
        content: this.content,
        receiver: this.userNo,
        type: 1,
      }
      this.websock.send(JSON.stringify(data))
      this.content = ''
    },

    getChatList() {
      this.chatList = []
      this.$getApi.getChatList(this.userNoSelf).then(res=>{
        console.log(res)
        for(let i=0; i<res.data.chatList.length; i++) {
          let obj = res.data.chatList[i]
          obj.avatar = res.data.users[obj.receiver].userProfile
          obj.nickname = res.data.users[obj.receiver].userNickname
          if(res.data.latestMessage[obj.listId] !== undefined) {
            obj.latestMessage = res.data.latestMessage[obj.listId].content
            obj.listIndex = 1
          }
          else {
            obj.latestMessage = null
            obj.listIndex = 0
          }
          obj.latestTime = this.setLatestTime(obj.latestTime)
          if(obj.unread > 99)
            obj.unread = '99+'
          this.chatList.push(obj)
        }
        console.log(this.chatList)
        this.showChatList()
      }).catch(error=>{
        console.log(error)
      })
    },
    getMessageRecord(receiver,listId,avatar,nickname) {
      this.messageList = []
      this.listId = listId
      this.userNo = receiver
      this.nickname = nickname
      this.avatar = avatar
      this.$getApi.getMessageRecord(receiver,this.userNoSelf).then(res=>{
        for(let i=0; i<res.data.messageList.length; i++) {
          let obj = res.data.messageList[i]
          if(obj.isMine == true) {
            obj.avatar = this.avatarSelf
            obj.nickname = this.nicknameSelf
          } else {
            obj.avatar = avatar
            obj.nickname = nickname
          }
          if(i > 0)
            obj.sendDate = this.setSendTime(res.data.messageList[i-1].sendTime,obj.sendTime)
          else
            obj.sendDate = this.setFirstSendTime(obj.sendTime)

          this.messageList.push(obj)
        }
        // console.log(this.messageList)
      }).catch(error=>{
        console.log(error)
      })
    },
    setFirstSendTime(thisStr) {
      let date = new Date()
      let thisDate = new Date(thisStr)
      let year = thisDate.getFullYear()
      let month = thisDate.getMonth()+1
      let day = thisDate.getDate()
      let hour = thisDate.getHours()
      let minutes = thisDate.getMinutes()
      let seconds = thisDate.getSeconds()
      if(month<10) month = '0' + month
      if(day<10) day = '0' + day
      if(minutes<10) minutes = '0' + minutes
      if(seconds<10) seconds = '0' + seconds
      if (thisDate.getFullYear()===date.getFullYear() && thisDate.getMonth()===date.getMonth() && thisDate.getDate()===date.getDate())
        return hour+':'+minutes+':'+seconds
      else
        return year+'-'+month+'-'+day+' '+hour+':'+minutes+':'+seconds
    },
    setSendTime(lastStr,thisStr) {
      let date = new Date()
      let lastDate = new Date(lastStr)
      let thisDate = new Date(thisStr)
      let year = thisDate.getFullYear()
      let month = thisDate.getMonth()+1
      let day = thisDate.getDate()
      let hour = thisDate.getHours()
      let minutes = thisDate.getMinutes()
      let seconds = thisDate.getSeconds()
      if(month<10) month = '0' + month
      if(day<10) day = '0' + day
      if(minutes<10) minutes = '0' + minutes
      if(seconds<10) seconds = '0' + seconds
      let num = (thisDate-lastDate)/(1000*60)  //求出求出两个时间的时间差（分）
      if(num < 5)
        return null
      else if (thisDate.getFullYear()===date.getFullYear() && thisDate.getMonth()===date.getMonth() && thisDate.getDate()===date.getDate())
        return hour+':'+minutes+':'+seconds
      else
        return year+'-'+month+'-'+day+' '+hour+':'+minutes+':'+seconds
    },
    setLatestTime(dateStr) {
      let date = new Date()
      let latesDate = new Date(dateStr)
      let month = latesDate.getMonth()+1
      let day = latesDate.getDate()
      let hour = latesDate.getHours()
      let minutes = latesDate.getMinutes()
      if(month<10) month = '0' + month
      if(day<10) day = '0' + day
      if(minutes<10) minutes = '0' + minutes
      if(latesDate.getFullYear()===date.getFullYear() && latesDate.getMonth()===date.getMonth() && latesDate.getDate()===date.getDate())
        return hour+':'+minutes
      else if(latesDate.getFullYear()===date.getFullYear() && latesDate.getMonth()===date.getMonth() && date.getDate()-latesDate.getDate() === 1)
        return '昨天'
      else
        return month+'-'+day
    },
    setListIdRead(listId,index) {
      this.$getApi.setListIdRead(listId).then(res=>{
        console.log(res)
        this.chatList[index].unread = 0
      }).catch(error=>{
        console.log(error)
      })
    },
    scrollToBottom() {
      try {
        const toBottom = this.$refs["toBottom"];
        toBottom.scrollTop = toBottom.scrollHeight;
      } catch (e) {
        console.log(e)
      }
    },
    showChatList() {
      let receiver = window.sessionStorage.getItem('receiver')
      console.log(this.chatList)
      for(let i=0; i<this.chatList.length; i++) {
        if(receiver == this.chatList[i].receiver) {
          this.chatList[i].listIndex = 1
          this.getMessageRecord(receiver,this.chatList[i].listId,this.chatList[i].avatar,this.chatList[i].nickname)
          //listId,avatar,nickname
        }
      }
    },
    pushEmoji() {
      document.getElementById('send-textarea').focus()
      let keyUp = document.createEvent('KeyboardEvent');
      keyUp.initEvent("keyUp",true, true)
      // keyUp.view = window;
      // keyUp.ctrlKey = false;
      // keyUp.altKey = false;
      // keyUp.shiftKey = false;
      // keyUp.metaKey = true;
      // keyUp.keyCode = 188;
      document.dispatchEvent(keyUp)
    },
    searchChatList() {
      if(this.searchInput === '')
        return
      this.searchedChatList = []
      if(this.timer){
        clearTimeout(this.timer)
      }
      if(!this.searchInput){
        this.searchedChatList=[]
        //return list
      }
      this.timer=setTimeout(()=> {
        for (let i=0;i< this.chatList.length;i++){
          let list = this.chatList[i]
          //判断输入框中的值是否可以匹配到数据，如果匹配成功
          // if(list.nickname.search(this.searchInput) != -1||list.receiver.search(this.searchInput) != -1){
          if(list.nickname.includes(this.searchInput)){
          //向空数组中添加数据
            this.searchedChatList.push(this.chatList[i]);
          }
        }
        // console.log(this.searchedChatList)
      },100)
    },
    showSearchedList() {
      this.searchIndex = 1
    },
    hideSearchedList() {
      if(this.searchInput === '')
        this.searchIndex = 0
    },
    clearSearchInput() {
      this.searchInput = ''
      this.searchedChatList = []
      document.getElementById('search-user').focus()
    }

  },

  mounted() {
    this.getChatList()
    this.initWebSocket()
    console.log(this.searchInput)
  },

  destroyed() {
    this.websocketonclose()
    window.sessionStorage.clear()
  },

  updated(){
    this.scrollToBottom()
  },

  watch: {
    searchInput: {
      handler: function(newVal,oldVal) {
        if(newVal !== oldVal) {
          this.searchChatList()
          console.log(this.searchedChatList)
        }
        if(newVal === '') {
          this.searchedChatList = []
        }
      }
    }
  },
}
</script>

<style scoped>
.background {
  z-index: -20;
}
.chat-box {
  display: flex;
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  /* top: 8%; */
  margin: 0 auto;
  width: 1000px;
  height: 615px;
  /*min-height: 300px;*/
  background-color: rgba(255, 255, 255, 0.85);
  /* box-shadow:0 0 5px #bbbbbb; */
  overflow: hidden;
}
.chat-box-left {
  border-width:1px;
  border-bottom-style:none;
  border-top-style:none;
  border-left-style:none;
  border-right-style:solid;
  border-color: #eeeeee;
  width: 280px;
  height: 615px;
}
.search-box {
  height: 70px;
}
.search-user {
  display: inline-flex;
  box-sizing: border-box;
  outline-style: none ;
  border: 1px solid #e2e2e2;
  border-radius: 3px;
  padding: 9px;
  /*width: calc(100% - 20px);*/
  width: 100%;
  font-size: 15px;
  background-color: rgb(242, 245, 247);
}
.search-user:focus {
  border: 1px solid #555555;
}
.search-user::-webkit-input-placeholder {
  color: #bbbbbb;
}
.icon-clear {
  display: inline-flex;
  position: relative;
  float: right;
  font-size: 12px;
  cursor: pointer;
  bottom: 26px;
  right: 5px;
}
.icon-clear-style {
  font-size: 13px;
  color: #b8b8b8;
}
.text-resent {
  margin: 0;
  padding: 0 0 10px 20px;
  border-width:1px;
  border-bottom-style:solid;
  border-top-style:none;
  border-left-style:none;
  border-right-style:none;
  border-color: #eeeeee;
}
.chat-user-list {
  overflow-y:auto;
  max-height: 513px;
}
.chat-user {
  box-sizing: border-box;
  width: 100%;
  height: 64px;
  padding: 10px 20px 10px 30px;
  border-width:1px;
  border-bottom-style:solid;
  border-top-style:none;
  border-left-style:none;
  border-right-style:none;
  border-color: #eeeeee;
  cursor: pointer;
}
.user-list-avatar {
  border-radius: 20px;
  width:40px;
  height:40px;
  float: left;
  margin-right: 10px;
}
.user-list-name {
  float: top;
  display: inline;
  max-width: 145px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.latest-message {
  max-width: 145px;
  font-size: 12px;
  color: #bbbbbb;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  margin: 5px 0 0;
}
.latest-time {
  font-size: 12px;
  color: #bbbbbb;
}
.tip-online {
  display:block;
  position: absolute;
  background: #26ff00;
  border-radius:50%;
  width:8px;
  height:8px;
  /*top:0px;*/
  /*right:0px;*/
}
.tip-offline {
  display:block;
  position: absolute;
  background: #ff0000;
  border-radius:50%;
  width:8px;
  height:8px;
}
.tip-unRead {
  min-width: 15px;
  height: 15px;
  background: red;
  box-sizing: border-box;
  color: white;
  font-size: 10px;
  text-align: center;
  line-height: 15px;
  border-radius: 10px;
  padding: 0 2px;
  display: inline-block;
  float: right;
  margin-top: 7px;
}
.chat-box-right {
  width: 719px;
  height: 615px;
}
.user-info-name {
  font-size: 18px;
  font-weight: bold;
  text-align: center;
  padding: 20px 5px 10px;
  border-width:1px;
  border-bottom-style:solid;
  border-top-style:none;
  border-left-style:none;
  border-right-style:none;
  border-color: #eeeeee;
}
.message-box {
  height: 400px;
  overflow-y:auto;
  padding: 0 20px 0;
  border-width:1px;
  border-bottom-style:solid;
  border-top-style:none;
  border-left-style:none;
  border-right-style:none;
  border-color: #eeeeee;
}
.message-item {
  position:relative;
  margin-bottom: 20px;
}
.message-time {
  text-align: center;
  font-size: 12px;
  line-height: 20px;
  color: #999;
  padding: 15px 0 10px;
}
.message-content {
  position: relative;
  text-align: left;
  font-size: 14px;
  line-height: 20px;
  box-sizing: border-box;
}
.bubble {
  position: relative;
  left:55px;
  /*width: 400px;*/
  min-width: 20px;
  max-width: 400px;
  min-height: 20px;
  background: #f6f6f6;
  border-radius: 8px;
  padding: 10px 12px;
  margin-bottom: 10px;
}
.bubble:before {
  content:'';
  position:absolute;
  right:100%;
  top:14px;
  /*width:0;*/
  /*height:0;*/
  border-width:5px;
  border-style:solid;
  border-color:transparent;
  /*border-right-width:5px;*/
  border-right-color:currentColor;
  color: #f6f6f6;
}
.my-bubble {
  /*float: right;*/
  position: relative;
  /*left:190px;*/
  max-width: 400px;
  min-height: 20px;
  background-color: #048FFA;
  border-radius: 8px;
  padding: 10px 12px;
  margin-bottom: 10px;
  margin-right: 10px;
  color: #ffffff;
}
.my-bubble:after {
  content:'';
  position:absolute;
  left:100%;
  top:14px;
  border-width:5px;
  border-style:solid;
  border-color:transparent;
  /*border-left-width:5px;*/
  border-left-color:currentColor;
  color: #048FFA;
}
.send-box {
  height: 200px;
  overflow-y:auto;
  padding: 10px;
}
.send-item {
  display: inline;
  padding-bottom: 10px;
}
.icon-style {
  display: inline-block;
  cursor: pointer;
  padding-right: 10px;
}
.icon-color {
  fill:currentColor;
  color: #555555;
}
.send-textarea {
  font-size: 15px;
  line-height: 23px;
  border: none;
  outline: none;
  resize:none;
  width: 98%;
}
.send-textarea:focus {
  border: none;
  outline: none;
}
.send-button {
  margin-right: 5px;
  padding: 7px;
  float: right;
  background-color: #048FFA;
  border-radius: 4px;
  width: 70px;
  color: #ffffff;
  text-align: center;
  font-size: 13px;
  outline: none;
  border: none;
  cursor: pointer;
}
.send-button:hover {
  background-color: #0083e8;
}
.send-button-none {
  margin-right: 5px;
  padding: 7px;
  float: right;
  background-color: #65b9ff;
  border-radius: 4px;
  width: 70px;
  color: #ffffff;
  text-align: center;
  font-size: 13px;
  outline: none;
  border: none;
}
.name {
  font-size: 85px;
  font-weight: 600;
  line-height: 615px;
  color: rgb(242, 245, 247);
  user-select: none;
}

</style>